package nautilus.lab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {
	static final int BLINK = 500;
	
	private boolean mCursorVisible = false;
	private Drawable mCursorDrawable;
	Rect mTempRect;
	Blink mBlink = null;
	long mShowCursor;
	
	public MyView(Context context) {
		super(context);
		
		mCursorDrawable = getResources().getDrawable(R.drawable.nmath_cursor_drawable);
		updateCursorPosition(0, 0, 0);
	}

	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mCursorDrawable = getResources().getDrawable(R.drawable.nmath_cursor_drawable);
		updateCursorPosition(0, 0, 0);
	}

	public MyView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mCursorDrawable = getResources().getDrawable(R.drawable.nmath_cursor_drawable);
		updateCursorPosition(0, 0, 0);
	}
	
	void updateCursorPosition(int top, int bottom, float horizontal) {
        if (mCursorDrawable == null)
            return;

//        if (mTempRect == null) mTempRect = new Rect();
//        mCursorDrawable.getPadding(mTempRect);
//        final int width = mCursorDrawable.getIntrinsicWidth();
//        horizontal = Math.max(0.5f, horizontal - 0.5f);
//        final int left = (int) (horizontal) - mTempRect.left;
//        mCursorDrawable.setBounds(left, top - mTempRect.top, left + width,
//                bottom + mTempRect.bottom);
        
        mCursorDrawable.setBounds(10, 5, 20, 35);
    }

	
	@Override
	protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        if(mCursorVisible)
        	mCursorDrawable.draw(canvas);
	}
	
	private class Blink extends Handler implements Runnable {
		private boolean mCancelled;
		@Override
		public void run() {
			if(mCancelled) return;
			removeCallbacks(Blink.this);
			mCursorVisible = !mCursorVisible;
			invalidate(10, 5, 20, 35);
			postAtTime(this, SystemClock.uptimeMillis() + BLINK);
		}
		
		void cancel() {
			if(!mCancelled) {
				removeCallbacks(Blink.this);
				mCancelled = true;
			}
		}
		
		void uncancel() {
			mCancelled = false;
		}
		
	}
	
	@Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);

        if(hasWindowFocus) {
        	if(mBlink == null)
        		mBlink = new Blink();
        	mBlink.removeCallbacks(mBlink);
        	mShowCursor = SystemClock.uptimeMillis();
        	mBlink.postAtTime(mBlink, mShowCursor + BLINK);
        } else {
        	mBlink.removeCallbacks(mBlink);
        }
    }
	
}
